<?php

namespace app\api\controller;

use addons\vip\library\Service;
use addons\vip\model\Record;
use addons\vip\model\Vip;
use app\admin\model\Bookclass;
use app\admin\model\Bookjie;
use app\admin\model\bookjieorder\Bookjieorder;
use app\admin\model\bookorder\Bookorder;
use app\admin\model\Books;
use app\admin\model\books\BookShelf;
use app\admin\model\books\Booksjie;
use app\admin\model\books\Browse;
use app\admin\model\Content;
use app\admin\model\content\Help;
use app\admin\model\needbook\Needbook;
use app\admin\model\rate\Rate;
use app\admin\model\sarch\Bookplan;
use app\admin\model\teacher\Share;
use app\admin\model\vip\Viporder;
use app\admin\model\vip\Viprecore;
use app\common\controller\Api;
use app\common\model\MoneyLog;
use Monolog\Handler\BrowserConsoleHandler;
use think\Db;
use think\Log;
use think\cache\driver\Redis;

/**
 * 我的接口
 */
class My extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];




    /**
     * 我得书架
     * @ApiMethod (GET)
     * @param int $token  token
     * @param int $keywords    keywords
     * */
    public function cateList(){

        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $where['a.user_id'] = $uid;

        $keywords = $this->request->get('keywords');

        $where['b.title|b.author|b.lead|b.jie']=array('like','%' . $keywords . '%');
        $bookList = Db::table('fa_bookshelf')
            ->alias('a')
            ->where($where)
            ->join('books b','a.book_id = b.id')
            ->order('a.updatetime desc')
            ->field('b.jie,a.id,b.title,b.author,b.mian_image,a.news,b.id as book_id')
            ->select();
                $bookList = $bookList->all();

        if (!empty($bookList)){
            foreach ($bookList as $key=>$value){
                $bookList[$key]['count'] = Db::table('fa_bookjie')->where('book_id',$value['book_id'])->count();
                $jielist = Db::table('fa_bookjie')->where('book_id',$value['book_id'])->field('id')->select();

                $browInfo = (new  Browse())
                    ->where(['uid'=>$uid,'book_id'=>$value['book_id']])
                    ->limit(1)
                    ->order('updatetime desc')
                    ->find();

                foreach ($jielist as $keys => $item) {

                    if (isset($item['id']) && $item['id'] == $browInfo['jie_id']) {
                        $bookList[$key]['jie_id'] = $keys+1;
                    }
                }

            }
        }

        $list['bookList']  = $bookList;
        $list['browInfo'] =  (new  Browse())
            ->alias('a')
            ->where(['a.uid'=>$uid])
            ->join('books b','a.book_id = b.id')
            ->join('bookjie c','a.jie_id = c.id')
            ->limit(1)
            ->order('a.updatetime desc')
            ->field('a.mark,a.id,b.id as book_id,c.id as bookjie_id,b.title as book_title,b.author,b.mian_image,c.title as jie_title')
            ->select();

        $this->success('请求成功',$list);
    }



    /**
     * 加入书架
     * @ApiMethod (GET)
     * @param int id 图书id
     
     **/
    public function add_shelf(){
        $token = $this->auth->getToken();
        $id = $this->request->get('id');

        $uid = $this->getToken($token);

        $count = (new Books())->where(['status'=>1,'id'=>$id])->count();
        if ($count < 1){
            $this->error('图书不存在');
        }
        $browInfo =  (new  Browse())->where(['uid'=>$uid,'book_id'=>$id])->find();

        Db::startTrans();
        try {

//            if ($browInfo){
//                $result1 =(new Browse())->where('id',$browInfo['id'])->update(['updatetime'=>time()]);
//            }else{
//                $result1 =(new Browse())->insert(['uid'=>$uid,'book_id'=>$id,'createtime'=>time(),'updatetime'=>time()]);
//            }
            $shelf =(new BookShelf())->where(['user_id'=>$uid,'book_id'=>$id])->find();
            if ($shelf){
                $result =(new BookShelf())->where('id',$shelf['id'])->update(['updatetime'=>time()]);
            }else{
                $result =(new BookShelf())->insert(['user_id'=>$uid,'book_id'=>$id,'createtime'=>time(),'updatetime'=>time()]);
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        $this->success('成功',$result);


    }

    /**
     * 从书架删除
     * @ApiMethod (GET)
     * @param int id 书架id
     
     **/
    public function adel_shelf(){
        $token = $this->auth->getToken();
        $id = $this->request->get('id');

        $uid = $this->getToken($token);
        $shelf =(new BookShelf())->where(['user_id'=>$uid,'book_id'=>$id])->count();
        if ($shelf < 1){
            $this->error('记录不存在');
        }

        $result =(new BookShelf())->where(['user_id'=>$uid,'book_id'=>$id])->delete();

        if ($result){
            $this->success('成功');
        }
    }

    /**
     * 浏览历史
     * @ApiMethod (GET)
     
     **/
    public function browseList(){
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);

        $bookList = (new Browse())->getList(['uid'=>$uid]);

        if (!empty($bookList)){
            foreach ($bookList as $key=>$value){
                $bookList[$key]['count'] = Db::table('fa_bookjie')->where('book_id',$value['book_id'])->count();
                $jielist = Db::table('fa_bookjie')->where('book_id',$value['book_id'])->field('id')->select();
                $browInfo = (new  Browse())
                    ->where(['uid'=>$uid,'book_id'=>$value['book_id']])
                    ->limit(1)
                    ->order('updatetime desc')
                    ->find();
                foreach ($jielist as $keys => $item) {
                    if (isset($item['id']) && $item['id'] == $browInfo['jie_id']) {
                        $bookList[$key]['jie_now'] = $keys+1;
                    }
                }
            }
        }


        $this->success('成功',$bookList);
    }

    /**
     * 添加浏览历史
     * @ApiMethod (GET)
     
     * @param int book_id 书籍id
     **/
    public function browseAdd(){
        $token = $this->auth->getToken();
        $book_id = $this->request->get('book_id');
        $uid = $this->getToken($token);

        $info = (new Browse())->where(['uid'=>$uid,'book_id'=>$book_id])->find();

        if ($info){
            $result = (new Browse())->where(['id'=>$info['id']])->update(['updatetime'=>time()]);
        }else{
            $result = (new Browse())->insert(['book_id'=>$book_id,'uid'=>$uid,'createtime'=>time(),'updatetime'=>time()]);
        }
        $this->success('成功',$result);
    }


    /**
     * 删除浏览历史
     * @ApiMethod (GET)
     
     * @param int id 浏览历史id
     **/
    public function browseDel(){
        $token = $this->auth->getToken();
        $id = $this->request->get('id');
        $uid = $this->getToken($token);

        $info = (new Browse())->where(['uid'=>$uid,'id'=>$id])->find();

        if ($info){
            $result = (new Browse())->where(['id'=>$info['id']])->delete();
        }else{
            $this->error('记录不存在');
        }
        $this->success('成功',$result);
    }

    /**
     * 设置阅读偏好
     * @ApiMethod (GET)
     
     * @param int like 偏好1男生2女生
     **/
    public function editLike(){

        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $like = $this->request->get('like');

        $result = (new \app\common\model\User())->where('id',$uid)->update(['like'=>$like]);
        $this->success('成功',$result);

    }

    /**
     * 完结榜
     * @ApiMethod (GET)
     **/
    public function renew(){
        $list =  (new Books())->where(['isend'=>1,'status'=>1])->order('updatetime desc')->select();
        $this->success('成功',$list);

    }

    /**
     * 热门标签
     * @ApiMethod (GET)
     * @param string like 1男2女
     **/
    public function hot(){
        $like = $this->request->get('like');
        if ($like == 2){
            $catid = 4;
        }else{
            $catid = 1;
        }

        $erList =  (new Bookclass())->where(['bookclass_id'=>$catid,'status'=>1])->order('weigh desc')->select();

        $erChar = '';
        foreach ($erList as $key=>$value){
            if ($key == 0){
                $erChar .= $value['id'];
            }else{
                $erChar .= ','.$value['id'];
            }
        }

        //二级分类列表
        $catewhere = "status = 1";
        $catewhere .= " && bookclass_id In (".$erChar.")";
        $cateList = (new Bookclass())->where($catewhere)->order('weigh desc')->select();
        foreach ($cateList as $key=>$value){
            $cateList[$key]['books'] = (new Books())->where(['bookclass_id'=>$value['id'],'status'=>1])->limit(6)->order('check desc')->select();
        }

        $this->success('成功',$cateList);
    }

    /**
     * 排行帮
     * @ApiMethod (GET)
     **/
    public function paihang(){
//        $like = $this->request->get('like');
//        if ($like == 2){
//            $catid = 4;
//        }else{
//            $catid = 1;
//        }

//        $erList =  (new Bookclass())->where(['bookclass_id'=>$catid,'status'=>1])->order('weigh desc')->select();
//
//        $erChar = '';
//        foreach ($erList as $key=>$value){
//            if ($key == 0){
//                $erChar .= $value['id'];
//            }else{
//                $erChar .= ','.$value['id'];
//            }
//        }

        //二级分类列表
//        $catewhere = "status = 1";
//        $catewhere .= " && bookclass_id In (".$erChar.")";
//        $cateList = (new Bookclass())->where($catewhere)->order('weigh desc')->select() ;
//        foreach ($cateList as $key=>$value){
//            $cateList[$key]['books'] = (new Books())->where(['bookclass_id'=>$value['id'],'status'=>1])->limit(6)->order('check desc')->select();
//        }



        $cateList = [
            0=> [
               "name" => "完本榜",
               "type" => "isend",
            ],
            1=> [
                "name" => "推荐榜",
                "type" => "push",
            ],
            2=> [
                "name" => "口碑榜",
                "type" => "hot",
            ],
            3=> [
                "name" => "高分榜",
                "type" => "type",
            ],
        ];

        foreach ($cateList as $key=>$value){
            if ($value['type'] != 'type'){
                $cateList[$key]['books'] = (new Books())->where([$value['type']=>1,'status'=>1])->limit(6)->order('updatetime desc')->select();
            }else{
                $cateList[$key]['books'] = (new Books())->where(['status'=>1])->limit(6)->order('check desc')->select();
            }
        }

        $this->success('成功',$cateList);
    }


    /**
     * 求书
     * @ApiMethod (GET)
     
     * @param string title 标题
     * @param string author 作者
     * @param string phone 电话号
     * @param string lead 主角
     **/
    public function needbook(){
        $token = $this->auth->getToken();
        $lead = $this->request->get('lead');
        $phone = $this->request->get('phone');
        $author = $this->request->get('author');
        $title = $this->request->get('title');
        $uid = $this->getToken($token);
        $result = (new Needbook())->insert(['user_id'=>$uid,'lead'=>$lead,'phone'=>$phone,'author'=>$author,'title'=>$title,'createtime'=>time()]);
        $this->success('成功',$result);

    }

    /**
     * 查看更多
     * @ApiMethod (GET)
     * @param string bookclass_id 分类id
     **/
    public function moreList(){
        $bookclass_id = $this->request->get('bookclass_id');
        $list =  (new Books())->where(['bookclass_id'=>$bookclass_id,'status'=>1])->order('weigh desc')->select();
        $this->success('成功',$list);
    }

    /**
     * 搜索图书列表
     * @ApiMethod (GET)
     * @param string keywords 关键词
     **/
    public function search(){
        $keywords = $this->request->get('keywords');
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $where['title|author|lead|jie']=array('like','%' . $keywords . '%');
        $list =  (new Books())->where(['status'=>1])->where($where)->order('weigh desc')->select();
        if (!empty($list)){
            foreach ($list as $key=>$value){
                (new Books())->where(['id'=>$value['id']])->setInc('search_num');
            }
        }
        $data['list'] = $list;
        $data['tuiList'] = (new Books())->where(['status'=>1,'push'=>1])->order('weigh desc')->limit(10)->select();

        $searchLInfo = Db::table('fa_serarch')->where(['user_id'=>$uid,'keywords'=>$keywords])->find();
        $user_info  = (new \app\admin\model\User())->find($uid);
        $type = $user_info['like'];
        if ($searchLInfo){
            Db::table('fa_serarch')->where(['keywords'=>$keywords])->update(['updatetime'=>time(),'type'=>$type,'number'=>$searchLInfo['number']+1]);
        }else{
            Db::table('fa_serarch')->insert(['user_id'=>$uid,'keywords'=>$keywords,'updatetime'=>time(),'type'=>$type,'createtime'=>time(),'number'=>1]);
        }
        $this->success('成功',$data);
    }


    /**
     * 搜索历史
     * @ApiMethod (GET)
     
     **/
    public function searchLog(){
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);

        $data['searchLInfo'] = Db::table('fa_serarch')->where(['user_id'=>$uid])->limit(9)->order('createtime desc')->select();
        $data['hotsearch'] = Db::table('fa_serarch')->limit(9)->order('number desc')->select();

        $nvcatid = 4;
        $nancatid = 1;
        $classModel = 'fa_bookclass';

        $nverList =  Db::table($classModel)->where(['bookclass_id'=>$nvcatid,'status'=>1])->order('weigh desc')->select();
        $nverChar = '';
        foreach ($nverList as $key=>$value){
            if ($key == 0){
                $nverChar .= $value['id'];
            }else{
                $nverChar .= ','.$value['id'];
            }
        }
        $catewhere = "status = 1";
        $catewhere .= " && bookclass_id In (".$nverChar.")";
        $nvcateList = Db::table($classModel)->where($catewhere)->limit(3)->order('weigh desc')->select();
        $nvsanChar = '';
        foreach ($nvcateList as $key=>$value){
            if ($key == 0){
                $nvsanChar .= $value['id'];
            }else{
                $nvsanChar .= ','.$value['id'];
            }
        }

        $nvcatewhere = "status = 1";
        $nvcatewhere .= " && bookclass_id In (".$nvsanChar.")";
        $nvsearch = Db::table('fa_books')->where($nvcatewhere)->limit(6)->field('id,title,mian_image,author,lead,money,score')->order('search_num desc')->select();


        $nanerList =  Db::table($classModel)->where(['bookclass_id'=>$nancatid,'status'=>1])->order('weigh desc')->select();
        $nanChar = '';
        foreach ($nanerList as $key=>$value){
            if ($key == 0){
                $nanChar .= $value['id'];
            }else{
                $nanChar .= ','.$value['id'];
            }
        }
        $catewhere = "status = 1";
        $catewhere .= " && bookclass_id In (".$nanChar.")";
        $nancateList = Db::table($classModel)->where($catewhere)->limit(3)->order('weigh desc')->select();
        $nansanChar = '';
        foreach ($nancateList as $key=>$value){
            if ($key == 0){
                $nansanChar .= $value['id'];
            }else{
                $nansanChar .= ','.$value['id'];
            }
        }

        $nancatewhere = "status = 1";
        $nancatewhere .= " && bookclass_id In (".$nansanChar.")";
        $nansearch = Db::table('fa_books')->where($nancatewhere)->limit(6)->field('id,title,mian_image,author,lead,money,score')->order('search_num desc')->select();


        $data['nansearch'] = $nansearch;
        $data['nvsearch'] = $nvsearch;
        $this->success('成功',$data);
    }
    /**
     * 清空搜索历史
     * @ApiMethod (GET)
     **/
    public function delsearchLog(){
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $searchLInfo = Db::table('fa_serarch')->where(['user_id'=>$uid])->delete();
        $this->success('成功',$searchLInfo);
    }

    /**
     * 推荐列表接口
     * @ApiMethod (GET)
     **/
    public function tuiList(){
        $data['tuiList'] = (new Books())->where(['status'=>1,'push'=>1])->order('weigh desc')->limit(10)->select();
        $this->success('成功',$data);
    }

    /**
     * 图书详情接口
     * @ApiMethod (GET)
     * @param string id 书本id
     * @param int page page页码
     * @param int sort page页码
     **/
    public function bookInfo(){
        $id = $this->request->get('id');
        $token = $this->auth->getToken();
        $page = $this->request->get('page');
        $sort = $this->request->get('sort');

//
        $uid = $this->getToken($token);
//
        $Redis = new Redis();
        $redisInfo = $Redis->get($id.'-'.$uid);
        if ($redisInfo != false){
            $this->success('成功',json_decode($redisInfo,true));
        }

        $info =  (new Books())
            ->alias('a')
            ->where(['a.id'=>$id,'a.status'=>1])
            ->join('fa_bookclass b','a.bookclass_id = b.id')
            ->field('a.*,b.name as catename')
            ->find();
        if (empty($info)){
            $this->error('图书不存在');
        }


        $info['updatetime'] = $this->format_dates($info['updatetime']);
        $info['zhang'] = [];
//      $info['jieList'] = (new Booksjie())->where(['book_id'=>$id])->limit($page,30)->order('weigh '.$sort)->select();
        $jieList = (new Booksjie())->where(['book_id'=>$id])->order('weigh '.$sort)->field('id,title')->select();
//        $userVip = (new Viprecore())->where(['user_id'=>$uid,'status'=>'active'])->find();
        $count = count($jieList);
//        foreach ($jieList as $key=>$value){
//            if($userVip){
//                $jieList[$key]['free'] = 1;
//            }else{
//                $jieList[$key]['free'] = $this->free($uid,$id,$value['id'],$key,$count,$sort);
//            }
//        }
        $info['jieList'] = $jieList;
        $info['zhang'] = (new Booksjie())->where(['book_id'=>$id])->limit(1)->order('weigh acs')->find();

        if ($info['zhang']){
            $info['zhang']['content'] = strip_tags($info['zhang']['content']);
        }
        $jia = (new BookShelf())->where(['user_id'=>$uid,'book_id'=>$id])->find();
        $info['verse'] = (new Booksjie())->where(['book_id'=>$id])->count();
        $info['is_rate'] = 0;
        $rateinfo = (new Rate())->where(['user_id'=>$uid,'book_id'=>$id])->find();
        if (!empty($rateinfo)){
            $info['is_rate'] = 1;
        }

        $info['rate'] = 10;
        if ((new Rate())->where(['book_id'=>$id])->count() > 0){
            $info['rate'] = (new Rate())->where(['book_id'=>$id])->sum('rate')/(new Rate())->where(['book_id'=>$id])->count();
        }

        if ($jia){
            $info['is_shelf'] = 1;
        }else{
            $info['is_shelf'] = 0;
        }
        $info['page'] = $page;

        $info['browse'] =  (new  Browse())
            ->alias('a')
            ->where(['a.uid'=>$uid])
            ->join('books b','a.book_id = b.id')
            ->join('bookjie c','a.jie_id = c.id')
            ->limit(1)
            ->order('a.updatetime desc')
            ->field('a.mark,a.id,b.id as book_id,c.id as bookjie_id,b.title as book_title,b.author,b.mian_image,c.title as jie_title')
            ->select();
//        $Redis->set($id.'-'.$uid,json_encode($info));

        $this->success('成功',$info);
    }

    public function free($userid,$bookid,$bookjie_id,$key,$count,$sort){
        $site = config('site');
        $info  = (new \app\admin\model\User())->find($userid);
        $bookInfo = (new Books())->find($bookid);

        $orderInfo = (new Bookjieorder())->where(['bookjie_id'=>$bookjie_id,'user_id'=>$userid])->find();
        if ($orderInfo){
            return  1;
        }

        if ($sort == 'asc'){
            $free = $site['free'];
            if ($count > 100){
                $free = $site['free2'];
            }
            if ($key+1 > $free){
                return 0;
            }
            if ($key+1 <= $free){
                return 1;
            }
        }

        if($site['bookfree'] == 0){
            return  1;
        }
        return 0;
    }




    function format_dates($time) {
        if($time <= 0) return '刚刚';

        $nowtime = time();
        if ($nowtime <= $time) {
            return "刚刚";
        }

        $t = $nowtime - $time;
        $f = array(
            '31536000' => '年',
            '2592000' => '个月',
            '604800' => '星期',
            '86400' => '天',
            '3600' => '小时',
            '60' => '分钟',
            '1' => '秒'
        );
        foreach ($f as $k => $v) {
            $c = floor($t/$k);
            if ($c > 0) {
                return $c . $v . '前';
            }
        }
    }


//    /**
//     * 个人信息
//     * @ApiMethod (POST)
//     
//     */
//    public function userInfo(){
//        $token = $this->auth->getToken();
//        $this->success('请求成功',$this->request);
//
//        $uid = $this->getToken($token);
//
//        $info  = (new \app\admin\model\User())->field('id,nickname,username,money,avatar')->find($uid);
//        $this->success('请求成功',$info);
//    }

    /**
     * 用户详情
     * @ApiMethod (GET)
     
     **/
    public function userInfo(){
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $info  = (new \app\admin\model\User())->field('id,nickname,username,money,avatar,like,autokou,userId,mobile,logst,invite_code,invite_rwm,score,id_card,birthday,gender')->find($uid);

        $info['first_children'] = 0;
        $info['all_children'] = 0;

        $site = config('site');
        $info['y_url'] = $site['y_url'];
        $info['y_ewm'] = $site['y_ewm'];
        $share = (new Share())->where(['user_id'=>$uid])->find();
        if ($share){
            $info['first_children'] = $share['first_children'];
            $info['all_children'] = $share['all_children'];
            $info['teacher_id'] = $share['teacher_id'];

            $teacher = Db::table('fa_view_teacher')->find($share['teacher_id']);
            $info['teacher_name'] = $teacher['name'];
        }

        $recordInfo = Record::getLastRecord($uid);
        $info['express'] = 0;
        if ($recordInfo){
            $info['express'] = date('Y-m-d',$recordInfo['expiretime']);
        }
        $site = config('site');
        $info['fee'] = $site['fee'];

        $this->success('请求成功',$info);
    }

    /**
     * 获取微信
     * @ApiMethod (GET)
     **/
    public function weixin(){
        $info['wechat'] = config('site.wechat');
        $info['wechat_h'] = config('site.wechat_h');

        $this->success('请求成功',$info);
    }


    /**
     * 帮助中心
     * @ApiMethod (GET)
     **/
    public function help(){
        $list = (new \app\admin\model\content\Content())->where('status',1)->order('weigh desc')->select();
        $this->success('请求成功',$list);
    }

    /**
     * 帮助中心详情
     * @ApiMethod (GET)
     * @param string id id
     **/
    public function helpInfo(){
        $id = $this->request->get('id');
        $list = (new \app\admin\model\content\Content())->where('status',1)->where('id',$id)->find();
        $this->success('请求成功',$list);
    }

    /**
     * 意见反馈
     * @ApiMethod (GET)
     * @param string content 反馈内容
     * @param string phone 电话号
     * @param string wechat 微信
     
     **/
    public function feedback(){
        $token = $this->auth->getToken();
        $phone = $this->request->get('phone');
        $content = $this->request->get('content');
        $wechat = $this->request->get('wechat');
        $uid = $this->getToken($token);
        $result = (new Help())->insert(['content'=>$content,'phone'=>$phone,'wechat'=>$wechat,'user_id'=>$uid,'createtime'=>time()]);
        $this->success('请求成功',$result);
    }


    /**
    * 猜你喜欢
    * @ApiMethod (GET)
    **/
    public function like(){
/*        $user = $this->auth->getUser();
*/
        // if ($token != '' && $like == 0){
        //     $uid = $this->getToken($token);
        //     $userInfo = (new \app\admin\model\User())->find($uid);
        //     $like = $userInfo['like'];
        // }
        // if ($like == 2){
        //     $catid = 4;
        // }else{
        //     $catid = 1;
        // }
                $page = $this->request->get('page');

     $result = (new Books())->where(['status'=>1])->limit($page,10)->order('weigh desc')->select();

        // $result = (new Books())->where(['status'=>1])->order('weigh desc')->limit(10)->page->select();
        $this->success('请求成功',$result);
    }



    /**
     * 获取充值配置
     * @ApiMethod (GET)
     **/
    public function moneyConfig(){
        $list = (new \app\admin\model\money\Money())->where('status',1)->order('weigh desc')->select();
        $this->success('请求成功',$list);
    }


    /**
     * 设置自动扣费
     * @ApiMethod (GET)
     * @param string autokou 1是0否
     
     **/
    public function autokou(){
        $token = $this->auth->getToken();
        $autokou = $this->request->get('autokou');
        $uid = $this->getToken($token);
        $userInfo = (new \app\admin\model\User())->find($uid);

        if ($userInfo['autokou'] == $autokou){
            $this->error('无需修改');
        }
        $result = (new \app\admin\model\User())->where('id',$uid)->update(['autokou'=>$autokou]);
        $this->success('请求成功',$result);
    }

    /**
     * 章节详情
     * @ApiMethod (GET)
     * @param string bookjie_id 章节id
     **/
    public function jieInfo(){
        $bookjie_id = $this->request->get('bookjie_id');

        $jieInfo = (new Booksjie())->where('id',$bookjie_id)->find();
        if (!$jieInfo){
            $this->error('章节不存在');
        }

        $this->success('获取成功',$jieInfo);
    }

    /**
     * 开始阅读
     * @ApiMethod (GET)
     * @param string bookjie_id 章节id
     
     **/
    public function stratLook(){
        $token = $this->auth->getToken();
        $bookjie_id = $this->request->get('bookjie_id');
        $mark = 1;
        $uid =$this->getToken($token);
        $info  = (new \app\admin\model\User())->find($uid);
        $site = config('site');

        $jieInfo = (new Booksjie())->where('id',$bookjie_id)->find();
        if (!$jieInfo){
            $this->error('章节不存在');
        }
        $last = (new Booksjie())->where('weigh', '<', $jieInfo['weigh'])->where(['book_id'=>$jieInfo['book_id']])->order('weigh', 'desc')->limit(1)->find();
        if(empty($last)){
            $last = (new Booksjie())->where(['book_id'=>$jieInfo['book_id']])->order('weigh', 'desc')->limit(1)->find();
        }
        $next = (new Booksjie())->where('weigh', '>', $jieInfo['weigh'])->where(['book_id'=>$jieInfo['book_id']])->order('weigh', 'acs')->limit(1)->find();
        if(empty($next)){
            $next = (new Booksjie())->where(['book_id'=>$jieInfo['book_id']])->order('weigh', 'acs')->limit(1)->find();
        }

        $jieInfo['verse'] = (new Booksjie())->where(['book_id'=>$jieInfo['book_id']])->count();

        $data['jieInfo'] = $jieInfo;
        $data['last'] = $last;
        $data['next'] = $next;
        $data['usermoney'] = $info['money'];
        $data['bookinfo'] = (new Books())->find($jieInfo['book_id']);
        $data['bookinfo']['money'] = $site['bookfree'];

        $resu = $this->isbuy($uid,$jieInfo['book_id'],$bookjie_id);

//        if ($resu == 0 && $info['autokou'] == 0){
//            $this->success('需要购买',$data,100);
//        }

        $orderInfo = (new Bookjieorder())->where(['bookjie_id'=>$bookjie_id,'user_id'=>$uid])->find();
        if (!$orderInfo && $resu == 0){
            if ($info['money'] < $site['bookfree']){
                $this->error('余额不足',$data,200);
            }
            Db::startTrans();
            try {
                \app\common\model\User::money(-$site['bookfree'],$uid,'购买章节');
                (new Bookjieorder())->insert(['user_id'=>$uid,'bookjie_id'=>$bookjie_id,'amount'=>$site['bookfree'],'createtime'=>time()]);
                $Redis = new Redis();
                $Redis->rm($jieInfo['book_id'].'-'.$uid);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
            }
        }

        //阅读历史
        $Bookplan = (new Bookplan())->where(['user_id'=>$uid,'book_id'=>$jieInfo['book_id']])->find();
        if($Bookplan){
            (new Bookplan())->where(['id'=>$Bookplan['id']])->update(['bookjie_id'=>$bookjie_id,'updatetime'=>time()]);
        }else{
            (new Bookplan())->insert(['user_id'=>$uid,'book_id'=>$jieInfo['book_id'],'bookjie_id'=>$bookjie_id,'createtime'=>time()]);
            (new Books())->where('id',$jieInfo['book_id'])->setInc('people_num');
        }

        $jieInfo['content'] = strip_tags(htmlspecialchars_decode($jieInfo['content']));

        $shelf =(new BookShelf())->where(['user_id'=>$uid,'book_id'=>$jieInfo['book_id']])->find();
        if ($shelf){
            (new BookShelf())->where('id',$shelf['id'])->update(['updatetime'=>time(),'news'=>0]);
        }else{
            (new BookShelf())->insert(['user_id'=>$uid,'book_id'=>$jieInfo['book_id'],'createtime'=>time(),'updatetime'=>time()]);
        }

        $Browse = (new Browse())->where(['uid'=>$uid,'book_id'=>$jieInfo['book_id']])->find();
        if ($Browse){
            $result = (new Browse())->where(['id'=>$Browse['id']])->update(['updatetime'=>time(),'jie_id'=>$bookjie_id,'mark'=>$mark]);
        }else{
            $result = (new Browse())->insert(['book_id'=>$jieInfo['book_id'],'uid'=>$uid,'jie_id'=>$bookjie_id,'createtime'=>time(),'updatetime'=>time(),'mark'=>$mark]);
        }

        $this->success('成功2',$data);
    }


    //判断是否购买
    public function isbuy($userid,$bookid,$bookjie_id){
        $site = config('site');
        $info  = (new \app\admin\model\User())->find($userid);

        $bookInfo = (new Books())->find($bookid);
        $jiecount = (new Bookjie())->where(['book_id'=>$bookid])->order('weigh asc')->select();

        $userVip = (new Viprecore())->where(['user_id'=>$userid,'status'=>'active'])->find();

        if($userVip){
            return 1;
        }
        $orderInfo = (new Bookjieorder())->where(['bookjie_id'=>$bookjie_id,'user_id'=>$userid])->find();
        if ($orderInfo){
            return  1;
        }
        $count = count($jiecount);
        foreach ($jiecount as $key=>$value){
            $free = $site['free'];
            if ($count > 100){
                $free = $site['free2'];
            }
            if ($value['id'] == $bookjie_id && $key+1 > $free){
                return 0;
            }
            if ($value['id'] == $bookjie_id && $key+1 <= $free){
                return 1;
            }
        }
        if($site['bookfree'] == 0){
            return  1;
        }
        return 0;
    }


    /**
     * 购买章节
     * @ApiMethod (GET)
     * @param string book_id 章节id
     
     **/
    public function buyBooksJie(){
        $token = $this->auth->getToken();
        $bookjie_id = $this->request->get('bookjie_id');
        $uid = $this->getToken($token);
        $info  = (new \app\admin\model\User())->find($uid);
        $site = config('site');

//        $jieInfo = (new Books())->where('id',$book_id)->find();
        $jieInfo = (new Booksjie())->where('id',$bookjie_id)->find();

        if (empty($jieInfo)){
            $this->error('章节不存在');
        }
//https://yc.ychlkj.cn/web/index.php?_mall_id=13&r=api/index/tpl-index&page_id=0
//        $order = (new Bookorder())->where(['book_id'=>$book_id,'user_id'=>$uid])->find();
        $order = (new Bookjieorder())->where(['bookjie_id'=>$bookjie_id,'user_id'=>$uid])->find();
        if ($order){
            $this->error('请勿重复购买');
        }

        if ($info['money'] < $site['bookfree']){
            $this->error('余额不足');
        }
        Db::startTrans();
        try {
            \app\common\model\User::money(-$site['bookfree'],$uid,'购买小说');
//            (new Bookorder())->insert(['user_id'=>$uid,'book_id'=>$book_id,'amount'=>$jieInfo['money'],'createtime'=>time()]);
            (new Bookjieorder())->insert(['user_id'=>$uid,'bookjie_id'=>$bookjie_id,'amount'=>$site['bookfree'],'createtime'=>time()]);
            $Redis = new Redis();
            $Redis->rm($jieInfo['book_id'].'-'.$uid);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        $this->success('成功');
    }

    /**
     * 消费记录
     * @ApiMethod (GET)
     
     **/
    public function moneyLog(){
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);

        $info['list'] = Db::table('fa_user_pay_log')->where('user_id',$uid)->order('createtime desc')->field('*,FROM_UNIXTIME(createtime, "%Y/%m/%d %H:%i:%s") as createtime')->select();
        $info['count'] = Db::table('fa_user_pay_log')->where('user_id',$uid)->sum('money');
        $this->success('成功',$info);
    }

    /**
     * 执行定时任务
     * @ApiMethod (GET)
     **/
    public function dingshi()
    {
        $time = time();
        //清理锁定且过期的数据
        Record::where('status', 'locked')->where('expiretime', '<', $time)->update(['status' => 'expired']);
        //判断用户VIP是否过期，-1表示全部
        Service::checkVipExpired(-1);
        echo "done";
    }

    /**
     * 小说评价
     * @ApiMethod (GET)
     * @param int bookid 书本id
     * @param int rate 评分
     * @param string token token
     **/
    public function rate(){
        $token = $this->auth->getToken();
        $bookid = $this->request->get('bookid');
        $rate = $this->request->get('rate');
        $uid = $this->getToken($token);
        $info = (new Rate())->where(['user_id'=>$uid,'book_id'=>$bookid])->find();
        if (!empty($info)){
            $this->success('无需重复评价',$info,100);
        }
        $info = (new Rate())->insert(['user_id'=>$uid,'book_id'=>$bookid,'rate'=>$rate,'createtime'=>time()]);
        $this->success('成功',$info);
    }




}
